package com.conversationboard.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.conversationboard.site.Site;

/**
 * Provides a point of interception for every request coming through the code. Useful for the
 * likes of preventing access to the site.
 * 
 * @author Keith Watson
 *
 */

public class GatewayFilter implements Filter {

	public void destroy() {
	}


	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		try {

			HttpServletRequest httpServletRequest = (HttpServletRequest) request;

			request.setAttribute("contextPath", httpServletRequest.getContextPath());

			if (!Site.isShut()) {
				chain.doFilter(request, response);
				return;
			}

			/* Are you an administrator */

			String access = request.getParameter("access");
			boolean ableToAccess = false;

			if ((access != null) && (access.equalsIgnoreCase("true"))) {
				httpServletRequest.getSession().setAttribute("access", "true");
				ableToAccess = true;
			} else {
				access = (String) httpServletRequest.getSession().getAttribute("access");

				if ((access != null) && (access.equalsIgnoreCase("true"))) {
					ableToAccess = true;
				}
			}

			if (ableToAccess) {
				request.setAttribute("siteshut", true);
				chain.doFilter(request, response);
				return;
			} else {
				request.setAttribute("message", "Site is closed for maintenance. Please try again later");
				request.setAttribute("display", "showNoMenu");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");

				dispatcher.forward(request, response);
				return;
			}
			
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}


	public void init(FilterConfig config) throws ServletException {
	}

}
